<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-select class="selectClass" v-model="form.warehouse_id" placeholder="仓库" clearable multiple collapse-tags
          @change="changeWarehouse" @clear="changeWarehouse">
          <el-option v-for="item in wareDataList" :key="item.id" :label="item.warehouse_name"
            :value="item.id"></el-option>
        </el-select>
        <el-select class="selectClass w-30" v-model="form.floor_id" placeholder="楼层" clearable multiple collapse-tags
          @change="changeFloor" @clear="changeFloor">
          <el-option v-for="item in floorList" :key="item.id" :label="item.floor_name" :value="item.id"></el-option>
        </el-select>
        <el-select class="selectClass" v-model="form.area_id" placeholder="库区" clearable multiple collapse-tags>
          <el-option v-for="item in areaList" :key="item.id" :label="item.area_name" :value="item.id"></el-option>
        </el-select>
        <el-select class="selectClass" v-model="form.id" placeholder="货位类型" multiple>
          <el-option v-for="item in options['base.location']?.[0].locationType" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
        <el-input v-model="form.location_code" placeholder="货位编号" class="w-40"></el-input>
        <VGroup>
          <el-select class="selectClass" v-model="form.timeRange.type" style="max-width: 100px">
            <el-option v-for="item in timeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="form.timeRange.value" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime()" style="max-width: 300px" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="open('add')"><svg-icon class="text-white mr-1" icon-class="add"/>新增</el-button>
        <el-button @click="handleImport"><svg-icon icon-class="download01" />导入</el-button>
        <el-button @click="handlePrint">打印</el-button>
        <el-button class="ml-auto" @click="exportFile"><svg-icon icon-class="import" />导出</el-button>
      </template>
    </VTable>
    <ComModal ref="ComModalRef" :options="options" :wareDataList="wareDataList" @query="query"></ComModal>
    <importFile ref="importRef" type="location" :api="importLocation" @query="query"></importFile>
    <VLog ref="logRef" class="dialogPublic" :api="getLocationLog" options="id"></VLog>
  </VPage>
</template>
<script setup name="BaseLocation" lang="jsx">
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, ref, reactive, toRefs } from 'vue'
import { getEnums } from '@/api/public'
import { queryLocationList, getLocationLog, importLocation } from './api'
import { getWareDataFloor } from '@/api/public'
import ComModal from './components/ComModal.vue'
import importFile from '@/components/importFile';
import VLog from '@/components/VLog';
import { getLodop } from '@/utils/LodopFuncs.js';

const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "修改时间", value: "update_time" },
]

const tableRef = ref()
const tableOptins = reactive({
  rowConfig: { height: 60 },
  formConfig: {
    data: {
      warehouseRange: { type: 'warehouse_name', value: [], range: true },
      timeRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: "40" },
    {
      field: 'location_code', title: '货位编号'
    },
    {
      field: 'warehouse_name', title: '所属仓库'
    },
    {
      field: 'floor_name', title: '楼层'
    },
    {
      field: 'area_name', title: '库区',
    },
    {
      field: 'type_cn', title: '货位类型'
    },
    {
      field: 'pick_cn', title: '是否混放'
    },
    {
      field: 'status_cn', title: '是否启用'
    },
    {
      field: 'create_user', title: '创建人', width: 160
    },
    {
      field: 'create_time', title: '创建日期', width: 180
    },
    {
      field: 'update_user', title: '最近修改人', width: 160
    },
    {
      field: 'update_time', title: '修改日期', width: 180
    },
    {
      title: '操作', width: "160", fixed: "right", slots: {
        default: ({ row }) => {
          return <div class="table-option">
            <div>
              <el-link type="primary" underline={false} class="border-solid border-red border-r-1 mr-2" onClick={() => open('view', row.id)}>查看</el-link>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => open('edit', row.id)}>修改</el-link>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => viewLog(row)}>操作记录</el-link>
            </div>
          </div >
        }
      }
    }
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryLocationList({ ...form, ...page })
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total
          })
        })
      }
    }
  }
})
const query = () => {
  tableRef.value.query()
}

const data = reactive({
  options: [],
  wareDataList: [],
  floorList: [],
  areaList: []
})
const { options, wareDataList, floorList, areaList } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "base.location"
    ]
  }).then(res => {
    options.value = res.data
  })
}
fetchOption()

// 获取仓库
const getWareDataList = async () => {
  try {
    const res = await getWareDataFloor()
    wareDataList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}
// provide('wareDataList', wareDataList)
getWareDataList()


const changeWarehouse = async (val) => {
  console.log(val)
  let floors = []
  wareDataList.value.forEach(element => {
    if (val && val.includes(element.id)) {
      floors.push(...element.floors)
    }
  });
  floorList.value = floors
  areaList.value = []
  tableRef?.value.setFormField('floor_id', '')
  tableRef?.value.setFormField('area_id', '')
}

const changeFloor = async (val) => {
  let areas = []
  floorList.value.forEach(element => {
    if (val && val.includes(element.id)) {
      areas.push(...element.areas)
    }
  });
  areaList.value = areas
  tableRef?.value.setFormField('area_id', '')
}

const ComModalRef = ref()
const open = (type, id) => {
  ComModalRef.value.open(type, id)
}

//查看日志
const logRef = ref()
const viewLog = (id) => {
  logRef.value.open(id)
}

// 导入
const importRef = ref()
const handleImport = () => {
  nextTick(() => {
    importRef.value.open()
  })
}

// 导出
const exportFile = () => {
  ElMessage.error('暂未对接')
}

// 打印
const handlePrint = () => {
  const records = getSelectRow()
  if (records.length == 0) {
    ElMessage.error('至少选择一项')
    return
  }
  
  const LODOP = getLodop();
  // LODOP.ADD_PRINT_RECT(0, 0, "100.01mm", "60.01mm", 0, 1);
  LODOP.ADD_PRINT_RECT(0,0,300,200,0,1);
  LODOP.ADD_PRINT_TEXT(150, 20, 163, 33, "3F-01BA01");
  LODOP.SET_PRINT_STYLEA(0, "FontSize", 22);
  LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
  LODOP.ADD_PRINT_BARCODE(20, 20, 280, 100, "Code39", "3F-01BA01");
  LODOP.PREVIEW(); // 打印预览

}

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}

</script>